package cn.jarlen.jwt.tools.https;

import com.example.jarlen.myapplication.BuildConfig;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import cn.jarlen.jwt.tools.JwtToolApplication;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author jarlen
 * Create by 2024/7/18 11:26
 */
public class ApiManager {

    private static final String HTTPS_CERT_FILENAME = "server.cer";

    /**
     * keystore名称
     */
    private static final String KETSTORE_FILENAME = "server.bks";
    /**
     * keystore密码
     */
    private static final String KETSTORE_PASSWORD = "tomcat";

    public static final String CERT_156 = "-----BEGIN CERTIFICATE-----\n" +
            "MIICezCCAeSgAwIBAgIICxAAAAAAAOIwDQYJKoZIhvcNAQEFBQAwMTELMAkGA1UE\n" +
            "BhMCY24xDTALBgNVBAoTBHhkamExEzARBgNVBAMTClhkamFSb290Q2EwHhcNMTUw\n" +
            "NzAzMDMwNzIwWhcNMzUwNjI4MDMwNzIwWjA7MQswCQYDVQQGEwJjbjENMAsGA1UE\n" +
            "ChMEeGRqYTEPMA0GA1UECxMGZGV2aWNlMQwwCgYDVQQDEwMxNTYwgZ8wDQYJKoZI\n" +
            "hvcNAQEBBQADgY0AMIGJAoGBAJ6oyCPhYOOFo5HQD+yNRM64pEe3Pse1/uTCDZuJ\n" +
            "/bXCp6hby4mBAAxu5tHNEx4O1UvpdzfZoGuITPs0XkpaU5uRux3uN/nz/DxWmw0s\n" +
            "06SgNzgCxvMme9+/CNMwJyuWlzkCubsEFauQlZnrJeVf9Z5mauAEjj6yGkzovvc/\n" +
            "WhK/AgMBAAGjgZEwgY4wHwYDVR0jBBgwFoAUHiHQ3Ee7Yiyqg0zUCTgCNX6ekrww\n" +
            "HQYDVR0OBBYEFNZAFLH7b4G99FDYetVJvOUY6dCLMAkGA1UdEwQCMAAwQQYDVR0f\n" +
            "BDowODA2oDSgMoYwaHR0cDovL3NzcGZjcmwueGRqYS5jb20vQ3JsRG93bmxvYWQ/\n" +
            "ZHA9cm9vdDAuY3JsMA0GCSqGSIb3DQEBBQUAA4GBAEL+1EyPyapeKmk3D1stXBBe\n" +
            "eaKV1q1v9HuHvihfhq6/Za9G30drT6Qbr77RfUAfwMpCV6LiQoY0q7gPPxFRSP/H\n" +
            "AY8szLChKUBHjzOb5qYPwCcZeR7cOu3dJloYM+Uolh1+egqqyJSK+p9mhcl23uku\n" +
            "dkqlbG9oD+f6NO6HiCBP\n" +
            "-----END CERTIFICATE-----\n";

    private static ApiManager instance = null;
    private final Object monitor = new Object();
    private Retrofit.Builder mRetrofitBuild;
    private OkHttpClient.Builder mOkHttpClientBuild;
    private static final long DEFAULT_TIME_OUT = 60;

    private SampleApi sampleApi;

    public ApiManager() {
        InputStream certIns = null;
        InputStream keyStoreIns = null;
        try {
            // certIns = JwtToolApplication.getApplication().getAssets().open(HTTPS_CERT_FILENAME);
            certIns = new ByteArrayInputStream(CERT_156.getBytes());
            keyStoreIns = JwtToolApplication.getApplication().getAssets().open(KETSTORE_FILENAME);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream[] certInputStreams = new InputStream[]{certIns};
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(certInputStreams, keyStoreIns, KETSTORE_PASSWORD);
        mOkHttpClientBuild = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
        if (BuildConfig.DEBUG) {
            mOkHttpClientBuild.addInterceptor(getLoggingInterceptor());
        }
        mRetrofitBuild = new Retrofit.Builder()
                .baseUrl("https://11.12.108.50:8443/sample/")
                .client(mOkHttpClientBuild.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create());
    }

    /**
     * 获取ApiManager单例
     *
     * @return apiManager实例
     */
    public static ApiManager getInstance() {
        if (instance == null) {
            synchronized (ApiManager.class) {
                if (instance == null) {
                    instance = new ApiManager();
                }
            }
        }
        return instance;
    }

    /**
     * 根据泛型类型创建相关API
     *
     * @param apiClass api class
     * @param <T>      泛型类型
     * @return api接口
     */
    private <T> T createApi(Class<T> apiClass) {
        return mRetrofitBuild.build()
                .create(apiClass);
    }

    /**
     * 根据泛型类型创建相关API
     *
     * @param baseUrl  url地址
     * @param apiClass api class
     * @param <T>      泛型类型
     * @return api接口
     */
    public <T> T createApi(String baseUrl, Class<T> apiClass) {
        mRetrofitBuild.baseUrl(baseUrl);
        return createApi(apiClass);
    }

    /**
     * 创建pams接口api
     *
     * @return
     */
    public SampleApi createSampleApi() {
        if (sampleApi == null) {
            synchronized (monitor) {
                if (sampleApi == null) {
                    sampleApi = createApi("https://11.12.108.50:8443/sample/", SampleApi.class);
                }
            }
        }
        return sampleApi;
    }

    private static HttpLoggingInterceptor getLoggingInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }
}
